package com.eastfair.visitor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.venuebooking.dto.SpacePageQuery;
import com.eastfair.venuebooking.entity.Space;
import com.eastfair.venuebooking.vo.SpaceVO;
import com.eastfair.visitor.dao.DepartmentMapper;
import com.eastfair.visitor.entity.Department;
import com.eastfair.visitor.entity.ReservationAuditRecord;
import com.eastfair.visitor.service.DepartmentService;
import com.eastfair.boot.service.SuperServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.eastfair.visitor.vo.*;
import com.eastfair.visitor.dto.*;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 业务实现类
 * 部门管理
 * </p>
 *
 * @author lyw
 * @date 2022-11-18
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class DepartmentServiceImpl extends SuperServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Department> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<Department> list(DepartmentDTO modelDTO, List<Long> ids) {
        return ((DepartmentService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }

    @Override
    protected R<Boolean> handlerSave(Department model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'departmentName', #args[0]?.departmentName}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<Department> listOfCache(DepartmentDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getDepartmentName()), Department::getDepartmentName, modelDTO.getDepartmentName());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(Department::getId, ids);
        }
        queryWrapper.lambda().eq(Department::getIsDeleted, BusinessConstant.DELETE_NO);
        List<Department> modelList = list(queryWrapper);
        return modelList;
    }

    /**
     * 查询部门列表分页
     *
     * @param params
     * @return
     */
    @Override
    public IPage<DepartmentVO> queryDepartmentList(PageParams<DepartmentPageQuery> params) {
        log.info("DepartmentServiceImpl +++++ queryDepartmentList - 查询部门列表分页 params={}", JSONObject.toJSON(params));
        handlerQueryParams(params);
        Page<Department> page = params.buildPage();
        DepartmentPageQuery departmentPageQuery = params.getModel();
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Department::getIsDeleted, BusinessConstant.DELETE_NO)
                .like(StrUtil.isNotBlank(departmentPageQuery.getDepartmentName()),
                        Department::getDepartmentName, departmentPageQuery.getDepartmentName())
               .orderByDesc(Department::getCreateTime);
        page = page(page, queryWrapper);
        Page<DepartmentVO> resultPage = ConvertUtil.convertPage(page, DepartmentVO.class);
        return resultPage;
    }

    /**
     * 查询部门列表
     * @return
     */
    @Override
    public List<DepartmentVO> getDepartmentList() {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Department::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(Department::getIsEnabled,BusinessConstant.YES)
                .orderByDesc(Department::getCreateTime);
        List<Department> list = list(queryWrapper);
        List<DepartmentVO> departmentVOList = ConvertUtil.convertList(list, DepartmentVO.class);
        return departmentVOList;
    }

    /**
     * 添加部门
     *
     * @param departmentSaveDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveDepartmentInfo(DepartmentSaveDTO departmentSaveDTO) {
        log.info("DepartmentServiceImpl +++++ saveDepartmentInfo - 添加部门 departmentSaveDTO={}", JSONObject.toJSON(departmentSaveDTO));
        Department department = BeanUtil.toBean(departmentSaveDTO, Department.class);
        boolean save = save(department);
        return save;
    }

    /**
     * 修改部门
     *
     * @param departmentUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDepartmentInfo(DepartmentUpdateDTO departmentUpdateDTO) {
        log.info("DepartmentServiceImpl +++++ updateDepartmentInfo - 添加部门 departmentUpdateDTO={}", JSONObject.toJSON(departmentUpdateDTO));
        Department department = BeanUtil.toBean(departmentUpdateDTO, Department.class);
        departmentMapper.updateById(department);
        return Boolean.TRUE;
    }

    /**
     * 逻辑删除部门
     *
     * @param departmentUpdateDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delDepartmentById(DepartmentUpdateDTO departmentUpdateDTO) {
        log.info("DepartmentServiceImpl +++++ delDepartmentById - 逻辑删除部门 departmentUpdateDTO={}", JSONObject.toJSON(departmentUpdateDTO));
        Department department = BeanUtil.toBean(departmentUpdateDTO, Department.class);
        department.setIsDeleted(1);
        departmentMapper.updateById(department);
        return Boolean.TRUE;
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public DepartmentVO doToVo(Department model) {
        DepartmentVO modelVo = new DepartmentVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<DepartmentVO> doToVos(List<Department> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<DepartmentVO> result = new ArrayList<>();
        for (Department model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    public void handlerQueryParams(PageParams<DepartmentPageQuery> params) {
        if (StrUtil.isBlank(params.getSort()) || StrUtil.isBlank(params.getOrder())) {
            params.setSort("createTime");
            params.setOrder("descending");
        }
    }
}
